import O1HD from "../../engines/gameEngine";
import { CsvFileKind } from "../../engines/libs/CsvFileKind";
import data_control from "../../engines/libs/data_control";
import level_peopleArchery from "../../levelBundles/level_PeopleArchery/level_peopleArchery";
import PageBase from "../Base/PageBase";
import { IPagePramsBase } from "../Interface";
import mainRoot from "../MainRoot";

const {ccclass, property} = cc._decorator;

@ccclass
export default class peopleArcheryRouGePage extends PageBase {

    @property({type:cc.Node,tooltip:"item节点"})
    item:cc.Node = null;

    @property({type:cc.Node,tooltip:"itemContent"})
    itemContent:cc.Node = null;

    @property({type:cc.SpriteFrame,tooltip:"有可合成的显示图片"})
    canSyncSpf:cc.SpriteFrame = null;
    @property({type:cc.SpriteFrame,tooltip:"没有可合成的显示图片"})
    noSyncSpf:cc.SpriteFrame = null;

    datas:any[] = [];

    ariseIds:string[] = [];

    oldAriseIds:string[] = [];

    maxCount:number = 3;

    level:level_peopleArchery = null;

    selectId:string = "";

    async OnPageOpen(prams: IPagePramsBase): Promise<void> {
        super.OnPageOpen(prams);
        let ids = O1HD.getManagers().csvDataManager.getCsvIds(CsvFileKind.CsvFile.peopleArcheryMagicWeapon);
        let ariseDataAry:any[] = [];
        for(let id of ids){
            let data = O1HD.getManagers().csvDataManager.getCsvDataItem(CsvFileKind.CsvFile.peopleArcheryMagicWeapon,id);
            if(data["arise_flag"] == "1"){
                ariseDataAry.push(data);
            }
        }
        this.datas = ariseDataAry;
    }

    bindLevel(level:level_peopleArchery){
        this.level = level;
        this.loadPage();
        this.level.gamePauseFlag = true;
    }

    loadPage(){
        let needCreateCount:number = this.maxCount - this.itemContent.childrenCount;
        if(needCreateCount >0){
            for(let i = 0; i<needCreateCount; i++){
                let item:cc.Node = cc.instantiate(this.item);
                item.active = true;
                item.setParent(this.itemContent);
                item.on('touchend',this.onSelectItem,this);
            }
        }
        let ariseIds:string[] = this.oldAriseIds.concat();
        this.ariseIds = [];
        this.itemContent.children.forEach((n:cc.Node)=>{
            let randData = data_control.getRandItemOfArray(this.datas);
            let randId:string = randData["id"];
            while(ariseIds.includes(randId)){
                randData = data_control.getRandItemOfArray(this.datas);
                randId = randData["id"];
            }
            ariseIds.push(randId);
            this.ariseIds.push(randId);
            let id = randId;
            this.refrenshItem(n,randData);
            let sp:cc.Sprite = n.getChildByName("icon").getComponent(cc.Sprite);
            let syncLb:cc.Node = n.getChildByName("lbSynsic");
            let lbParam:cc.Label = n.getChildByName("lbParam").getComponent(cc.Label);
            // 加载icon
            let iconPath:string = randData["icon_path"];
            mainRoot.LevelSystem.getOneTypeBundle(this.level.getLevelInfo().levelType).load(`selectWeapon/${iconPath}`,cc.SpriteFrame,(err,spf:cc.SpriteFrame)=>{
                if(err){
                    console.log("加载道具icon失败",err);
                    return;
                }
                sp.spriteFrame = spf;
            });
            let roleWeapons:string[] = this.level.role.getWeapons();
            let syncFlag:boolean = false;
            for(let weaponId of roleWeapons){
                let data = O1HD.getManagers().csvDataManager.getCsvDataItem(CsvFileKind.CsvFile.peopleArcheryMagicWeapon,weaponId);
                let can_synthesis_id = data["can_synthesis_id"];
                if(can_synthesis_id == id){
                    syncFlag = true;
                }
            }
            let bgSp:cc.Sprite = n.getChildByName("bg").getComponent(cc.Sprite);
            syncFlag = syncFlag && !this.level.role.synthesisFlag;
            if(syncFlag){
                bgSp.spriteFrame = this.canSyncSpf;
            }else{
                bgSp.spriteFrame = this.noSyncSpf;
            }
            syncLb.active = syncFlag;
            let param = randData["param"];
            lbParam.string = "";
            let pAry:string[] = param.split("&");
            let typeAry:string[] = [];
            let paramAry:number[] = [];
            pAry.forEach((p:string)=>{
                let strAry:string[] = p.split("|");
                typeAry.push(strAry["0"]);
                paramAry.push(Number(strAry["1"]));
            });
            for(let i =0; i<pAry.length;i++){
                let data = {param_type:typeAry[i],option_param:paramAry[i]};
                let chat = O1HD.getManagers().peopleArcheryManager.getOptionText(data);
                lbParam.string += chat + (i == 0 ? "\n" :"");
            }
        });
        this.oldAriseIds = this.ariseIds.concat();
    }

    refrenshItem(item:cc.Node,data:any){
        let name = data["name"];
        let lbName:cc.Label = item.getChildByName("lbName").getComponent(cc.Label);
        lbName.string = name;

        return;
        let iconPath:string = data["icon_path"];
        mainRoot.LevelSystem.getOneTypeBundle(this.level.getLevelInfo().levelType).load("")
    }

    onSelectItem(e:cc.Event.EventTouch){
        let node:cc.Node = e.target;
        let sliblingIndex:number = node.getSiblingIndex();
        let id = this.ariseIds[sliblingIndex];
        this.selectId = id;
        this.allNodeNotSelect();
        this.onBtnComit();
        // 将节点设置为选中状态
    }

    allNodeNotSelect(){
        // 将所有节点设置为未选中状态
    }

    onBtnComit(){
        if(!this.selectId){
            O1HD.getModules().uiControlModule.showMessageBox("请先选择法宝");
            return;
        }
        this.level.roleAddWeapon(this.selectId);
        this.level.gamePauseFlag = false;
        this.level.role.showTitle("2");
        this.ClosePage();
    }

    onBtnRefrensh(){
        if(O1HD.getServices().userSrv.getCoins() > 0){
            // 有广告币
            this.loadPage();
            O1HD.getServices().userSrv.setCoins(-1,true);
        }else{
            O1HD.getServices().miniGameSrv.getAppApiInstance().loadAndShowVideoAd(()=>{
                this.loadPage();
            },()=>{},null,"箭箭箭看广告刷新法宝")
        }
    }

    update(dt: number): void {
        this.level.gamePauseFlag = true;    
    }

    onDestroy(): void {
        this.level.gamePauseFlag = false;
    }
}
